package Servlet;

import Utils.DbUtil;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/UpdataServlet")
public class UpdataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        String tableName = req.getParameter("tableName");
        String[] columns = req.getParameterValues("column");
        String[] oldColumns = req.getParameterValues("oldColumn");

        Map<String,String> columnTypes = DbUtil.getColumnAndType(req, tableName);

        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("UPDATE ").append(tableName).append(" SET ");

        List<Object> params = new ArrayList<>();
        int count = 0;
        try {
            for (String column : columns) {
                String type = columnTypes.get(column);
                Object value = null;

                String paramValue = req.getParameter(column);
                if (!paramValue.isEmpty()) {
                    switch (type) {
                        case "INT":
                            value = Integer.parseInt(paramValue);
                            break;
                        case "VARCHAR":
                        case "CHAR":
                            value = paramValue;
                            break;
                        case "DOUBLE":
                            value = Double.parseDouble(paramValue);
                            break;
                        case "FLOAT":
                            value = Float.parseFloat(paramValue);
                            break;
                        default:
                            try {
                                throw new Exception("暂时不支持数据类型修改");
                            } catch (Exception e) {
                                req.setAttribute("error", e.getMessage());
                                RequestDispatcher rd = req.getRequestDispatcher("error.jsp");
                                rd.forward(req, resp);
                            }
                    }
                }

                if (value == null) {
                    sqlBuilder.append(column).append(" is NULL");
                } else {
                    sqlBuilder.append(column).append(" = ?");
                    params.add(value);
                }

                if (++count < columns.length) {
                    sqlBuilder.append(", ");
                }
            }
        }catch (NumberFormatException e){
            req.setAttribute("error", e.getMessage());
            RequestDispatcher rd = req.getRequestDispatcher("error.jsp");
            rd.forward(req, resp);
        }


        sqlBuilder.append(" WHERE ");
        count = 0;
        for (String oldColumn : oldColumns) {
            String type = columnTypes.get(oldColumn);
            Object value = null;

            String paramValue = req.getParameter(oldColumn + "_old");
            if (!paramValue.isEmpty()) {
                switch (type) {
                    case "INT":
                        value = Integer.parseInt(paramValue);
                        break;
                    case "VARCHAR":
                    case "CHAR":
                        value = paramValue;
                        break;
                    case "DOUBLE":
                        value = Double.parseDouble(paramValue);
                        break;
                    case "FLOAT":
                        value = Float.parseFloat(paramValue);
                        break;
                    default:
                        try {
                            throw new Exception("暂时不支持数据类型修改");
                        } catch (Exception e) {
                            req.setAttribute("error", e.getMessage());
                            RequestDispatcher rd = req.getRequestDispatcher("error.jsp");
                            rd.forward(req, resp);
                        }
                }
            }
            if (value == null) {
                sqlBuilder.append(oldColumn).append(" is NULL");
            }else if (value instanceof Float || value instanceof Double){
                String result_ = String.valueOf(value);
                if (result_.endsWith(".0")) {
                    value = (int)Float.parseFloat(paramValue);
                }else {
                    value = Float.parseFloat(paramValue);
                }
                sqlBuilder.append(oldColumn).append(" like ?");
                params.add(value);
            } else {
                sqlBuilder.append(oldColumn).append(" = ?");
                params.add(value);
            }

            if (++count < oldColumns.length) {
                sqlBuilder.append(" AND ");
            }
        }
        String sql = sqlBuilder.toString();
        System.out.println(sql);
        System.out.println(params.toString());
        DbUtil.executeUpdate(req, resp, sql, params.toArray());
        resp.sendRedirect("GetTableServlet?tableName="+tableName);
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }
}
